import { appIdentifier } from '@/config'
import { LocalFile } from '@/type'
import { convertFileSrc, invoke } from '@tauri-apps/api/core'
import { localDataDir } from '@tauri-apps/api/path'

/**
 * 文件保存系统
 */
class FileSaveManager {
  constructor() {
    this.init()
  }

  localPath: string = ''
  private async init() {
    this.localPath = await localDataDir()
  }
  public async saveFileToUrl(file: File, group: string): Promise<LocalFile> {
    if (!this.localPath) {
      await this.init()
    }
    const fileName = `${Date.now()}_${file.name}`
    const savePath = `${this.localPath}/${appIdentifier}/${group}/${fileName}`
    await invoke('save_file', {
      path: savePath,
      chunk: await file.arrayBuffer(),
    })
    const url = convertFileSrc(savePath)
    return {
      url,
      path: savePath,
    }
  }

  public async removeFile(localFile: LocalFile) {
    await invoke('remove_file', { path: localFile.path })
  }
}

export default new FileSaveManager()
